package cn.wind.xboot.framework.domain;

import cn.wind.xboot.core.utils.BlankUtil;
import cn.wind.xboot.core.utils.Underline2CamelUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.google.common.collect.Lists;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import org.apache.commons.lang3.StringUtils;

import java.io.Serializable;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author Xukk
 */
@Data
public class PageVo implements Serializable {

    private static final long serialVersionUID = 1L;

    @ApiModelProperty(value = "页号")
    private int pageNumber=1;

    @ApiModelProperty(value = "页面大小")
    private int pageSize=10;

    @ApiModelProperty(value = "排序字段")
    private List<String>  sort;

    @ApiModelProperty(value = "查询关键词")
    private String searchKey;

    @SuppressWarnings("unchecked")
    public IPage init() {
        Page page = new Page(this.getPageNumber(), this.getPageSize());
        if (BlankUtil.isNotBlank(this.sort)){
            List<String> sortNew=Lists.newArrayList();
            this.sort.forEach(v-> Arrays.stream(v.split(",")).forEach(t-> sortNew.add(t)));
            int begin = 0;
            boolean flag = false;
            for (int i = 0; i < sortNew.size(); i++) {
                if (i != 0) {
                    if (StringUtils.equalsIgnoreCase(sortNew.get(i), "ASC")) {
                        flag = true;
                        page.setAscs(sortNew.subList(begin, i).stream().map(v-> Underline2CamelUtil.camel2Underline(v,true)).collect(Collectors.toList()));
                        if ((i + 1) < sortNew.size()) {
                            begin = i + 1;
                        }
                    } else if (StringUtils.equalsIgnoreCase(sortNew.get(i), "DESC")) {
                        flag = true;
                        page.setDescs(sortNew.subList(begin, i).stream().map(v-> Underline2CamelUtil.camel2Underline(v,true)).collect(Collectors.toList()));
                        if ((i + 1) < sortNew.size()) {
                            begin = i + 1;
                        }
                    }
                }
            }
            if(!flag){
                page.setAscs(sortNew.stream().map(v-> Underline2CamelUtil.camel2Underline(v,true)).collect(Collectors.toList()));
            }
        }
        return page;
    }
    public void init(JSONObject jsonObject){
        Integer pageNumber= jsonObject.getInteger("pageNumber");
        Integer pageSize=jsonObject.getInteger("pageSize");
        if(pageNumber!=null){
            setPageNumber(pageNumber);
        }
        if(pageSize!=null){
            setPageSize(pageSize);
        }
        if (jsonObject.getJSONArray("sort") != null) {
            setSort(jsonObject.getJSONArray("sort").toJavaList(String.class));
        }
    }
}
